﻿using System.Collections.Generic;

namespace SingletonPattern
{
    /// <summary>
    /// QueueHelper
    /// </summary>
    public class QueueHelper<TEntity> where TEntity : class, new()
    {
        /// <summary>
        /// 实例化
        /// </summary>
        public static readonly QueueHelper<TEntity> Instance = new QueueHelper<TEntity>();
        private static readonly Queue<TEntity> _Queue = new Queue<TEntity>();

        /// <summary>
        /// 添加到队列
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public void Enqueue(TEntity t)
        {
            lock (_Queue)
            {
                _Queue.Enqueue(t);
            }
        }

        /// <summary>
        /// 队列对头出队
        /// </summary>
        /// <returns></returns>
        public TEntity Dequeue()
        {
            lock (_Queue)
            {
                if (_Queue.Count > 0)
                {
                    return _Queue.Dequeue();
                }
                else
                {
                    return default;
                }
            }
        }

        /// <summary>
        /// 尝试出队
        /// </summary>
        /// <returns></returns>
        public (bool hasEntity, TEntity entity) TryDequeue()
        {
            lock (_Queue)
            {
                if (_Queue.Count > 0)
                {
                    bool isOk = _Queue.TryDequeue(out TEntity entity);
                    return isOk ? (isOk, entity) : (isOk, default);
                }
                else
                {
                    return default;
                }
            }
        }

        /// <summary>
        /// 检查队里是否包含该元素
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public bool Contains(TEntity t) => _Queue.Contains(t);

        /// <summary>
        /// 获取队列元素数量
        /// </summary>
        /// <returns></returns>
        public int QueueCount { get; } = _Queue.Count;

        /// <summary>
        /// 清除队列元素
        /// </summary>
        public void ClearQueue() => _Queue.Clear();

    }
}
